package edu.ustb.efws.controller;

import edu.ustb.efws.controller.form.LoginForm;
import edu.ustb.efws.controller.vo.LoginVo;
import edu.ustb.efws.controller.vo.OkVo;
import edu.ustb.efws.controller.vo.ResultVo;
import edu.ustb.efws.base.domain.User;
import edu.ustb.efws.security.Credential;
import edu.ustb.efws.security.token.TokenService;
import edu.ustb.efws.base.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

/**
 * 通用接口
 *
 * @author TS Group
 */
@RestController
@RequestMapping("/main")
@Api(value = "/main", tags="通用接口")
public class MainController {

    private final UserService service;
    private final TokenService tokenService;

    @Autowired
    public MainController(UserService service, TokenService tokenService) {
        this.service = service;
        this.tokenService = tokenService;
    }

    @PostMapping(value = "/login", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("登录")
    public ResultVo<LoginVo<User>> login(@RequestBody @Valid LoginForm form) {
        User user = service.getAndValidate(form.getUsername(), form.getPassword());
        String[] roles = user.getAdmin() != null && user.getAdmin()? new String[]{"ROLE_ADMIN"} : new String[0];
        Credential credential = new Credential(user.getId(), user.getUsername(), roles, true);
        String token = tokenService.generate(credential);

        return ResultVo.success(new LoginVo<>(token, user));
    }

    @GetMapping(value = "logout", produces = APPLICATION_JSON_VALUE)
    @ApiOperation("用户退出")
    public ResultVo<OkVo> memberLogout(@RequestHeader(value = "token", required = false) String token,
                                       @RequestHeader(value = "Authorization", required = false) String auth){
        String t = "";
        if(StringUtils.isNotBlank(token)){
            t = token;
        }
        if(StringUtils.isNotBlank(auth)){
            t = StringUtils.trim(StringUtils.removeStart(auth, "Bearer"));
        }
        if(StringUtils.isNotBlank(t)){
            tokenService.destroy(token);
        }
        return ResultVo.success(new OkVo(true));
    }
}
